<template>
  <view class="accesscard-bg">
    <view style="height: 32rpx;"></view>
    <view class="card-section">
      <view class="section-title">基本信息</view>
      <view class="form-group">
        <view class="form-item" @click="selectProvince">
          <text class="item-label"><text class="required">*</text>省</text>
          <view class="item-content">
            <text :class="['select-value', provinceName ? 'selected' : '']">{{ provinceName || '请选择省' }}</text>
            <uni-icons type="right" size="18" color="#bfbfbf"></uni-icons>
          </view>
        </view>
        <view class="form-item" @click="selectCity">
          <text class="item-label"><text class="required">*</text>市</text>
          <view class="item-content">
            <text :class="['select-value', cityName ? 'selected' : '']">{{ cityName || '请选择市' }}</text>
            <uni-icons type="right" size="18" color="#bfbfbf"></uni-icons>
          </view>
        </view>
        <view class="form-item" @click="selectDistrict">
          <text class="item-label"><text class="required">*</text>区</text>
          <view class="item-content">
            <text :class="['select-value', districtName ? 'selected' : '']">{{ districtName || '请选择区' }}</text>
            <uni-icons type="right" size="18" color="#bfbfbf"></uni-icons>
          </view>
        </view>
        <view class="form-item" @click="selectTown">
          <text class="item-label"><text class="required">*</text>镇街</text>
          <view class="item-content">
            <text :class="['select-value', townName ? 'selected' : '']">{{ townName || '请选择镇街' }}</text>
            <uni-icons type="right" size="18" color="#bfbfbf"></uni-icons>
          </view>
        </view>
        <view class="form-item" @click="selectVillage">
          <text class="item-label"><text class="required">*</text>村居</text>
          <view class="item-content">
            <text :class="['select-value', villageName ? 'selected' : '']">{{ villageName || '请选择村居' }}</text>
            <uni-icons type="right" size="18" color="#bfbfbf"></uni-icons>
          </view>
        </view>
        <view class="form-item">
          <text class="item-label"><text class="required">*</text>联系电话</text>
          <view class="item-content input-content">
            <input type="text" v-model="phoneNumber" placeholder="请输入手机号或固定电话" class="input-field" placeholder-class="input-placeholder" />
          </view>
        </view>
      </view>
    </view>

    <view style="height: 32rpx;"></view>
    <view class="card-section">
      <view class="section-title">购买门禁卡</view>
      <view class="form-group">
        <view class="form-item">
          <text class="item-label">买卡数量</text>
          <view class="item-content input-content">
            <input type="number" v-model="quantity" placeholder="请输入购买数量" class="input-field" placeholder-class="input-placeholder"
              @input="onQuantityInput" maxlength="5" />
            <text v-if="priceList.length" class="single-price">单价{{ (Number((priceList.find(p => p.type === '3') || {}).price || 0)).toFixed(2) }}元/张</text>
          </view>
        </view>
      </view>
    </view>

    <view style="height: 32rpx;"></view>
    <view class="notice">
      <uni-icons type="info" size="18" color="#fa3534" style="margin-right:6rpx;" />
      <text>购买门禁卡请到本村流管站！</text>
    </view>

    <view style="height: 120rpx;"></view>
    <view class="footer">
      <view class="total">
        <text>合计：</text>
        <text class="amount">¥ {{ totalAmount }}</text>
      </view>
      <button class="buy-button" @click="submit">立即购买</button>
    </view>
  </view>
</template>

<script>
import { addOrderInfo, getDeptPrice, getDeptTree } from '@/api/login';
import request from '@/utils/request';
export default {
  data() {
    return {
      phoneNumber: '',
      quantity: '',
      provinceId: '', provinceName: '',
      cityId: '', cityName: '',
      districtId: '', districtName: '',
      townId: '', townName: '',
      villageId: '', villageName: '',
      deptTree: [],
      priceList: [],
      selectedPrice: null
    };
  },
  computed: {
    totalAmount() {
      const qty = Number(this.quantity);
      const priceObj = this.priceList.find(p => p.type === '3');
      const price = priceObj ? Number(priceObj.price) : 0;
      if (!qty || !price) return '0.00';
      return ((qty * price)).toFixed(2);
    }
  },
  onLoad() {
    uni.setNavigationBarTitle({ title: '购买门禁卡费' });
    this.getDeptTree();
    this.loadCachedData();
  },
  methods: {
    // Save form data to local storage
    saveFormDataToCache() {
      const cacheData = {
        phoneNumber: this.phoneNumber,
        quantity: this.quantity,
        provinceId: this.provinceId, 
        provinceName: this.provinceName,
        cityId: this.cityId, 
        cityName: this.cityName,
        districtId: this.districtId, 
        districtName: this.districtName,
        townId: this.townId, 
        townName: this.townName,
        villageId: this.villageId, 
        villageName: this.villageName,
        priceList: this.priceList,
      };
      uni.setStorage({
        key: 'accessCardFormData',
        data: cacheData
      });
    },
    
    // Load cached form data
    loadCachedData() {
      uni.getStorage({
        key: 'accessCardFormData',
        success: (res) => {
          if (res.data) {
            const data = res.data;
            this.phoneNumber = data.phoneNumber || '';
            this.quantity = data.quantity || '';
            this.provinceId = data.provinceId || '';
            this.provinceName = data.provinceName || '';
            this.cityId = data.cityId || '';
            this.cityName = data.cityName || '';
            this.districtId = data.districtId || '';
            this.districtName = data.districtName || '';
            this.townId = data.townId || '';
            this.townName = data.townName || '';
            this.villageId = data.villageId || '';
            this.villageName = data.villageName || '';
            if (data.priceList && data.priceList.length) {
              this.priceList = data.priceList;
              // 如果有镇街ID，尝试获取最新的门卡价格
              if (this.townId) {
                this.fetchCardPrice(this.townId);
              }
            }
          }
        }
      });
    },
    
    async getDeptTree() {
      try {
        const res = await getDeptTree();
        if (res.code === 200 && res.data && res.data.length) {
          this.deptTree = res.data;
        }
      } catch (e) {}
    },
    async selectProvince() {
      if (!this.deptTree.length) return;
      const provinceList = this.deptTree[0].children || [];
      const names = provinceList.map(p => p.label);
      uni.showActionSheet({
        itemList: names,
        success: ({tapIndex}) => {
          this.provinceName = provinceList[tapIndex].label;
          this.provinceId = provinceList[tapIndex].id;
          this.cityName = this.cityId = this.districtName = this.districtId = this.townName = this.townId = this.villageName = this.villageId = '';
          this.priceList = [];
          this.selectedPrice = null;
          this.saveFormDataToCache();
        }
      });
    },
    async selectCity() {
      if (!this.provinceId) { this.$modal.showToast('请先选择省'); return; }
      const province = (this.deptTree[0].children || []).find(p => p.id === this.provinceId);
      if (!province) return;
      const cityList = province.children || [];
      const names = cityList.map(c => c.label);
      uni.showActionSheet({
        itemList: names,
        success: ({tapIndex}) => {
          this.cityName = cityList[tapIndex].label;
          this.cityId = cityList[tapIndex].id;
          this.districtName = this.districtId = this.townName = this.townId = this.villageName = this.villageId = '';
          this.priceList = [];
          this.selectedPrice = null;
          this.saveFormDataToCache();
        }
      });
    },
    async selectDistrict() {
      if (!this.cityId) { this.$modal.showToast('请先选择市'); return; }
      const province = (this.deptTree[0].children || []).find(p => p.id === this.provinceId);
      if (!province) return;
      const city = (province.children || []).find(c => c.id === this.cityId);
      if (!city) return;
      const districtList = city.children || [];
      const names = districtList.map(d => d.label);
      uni.showActionSheet({
        itemList: names,
        success: ({tapIndex}) => {
          this.districtName = districtList[tapIndex].label;
          this.districtId = districtList[tapIndex].id;
          this.townName = this.townId = this.villageName = this.villageId = '';
          this.priceList = [];
          this.selectedPrice = null;
          this.saveFormDataToCache();
        }
      });
    },
    async selectTown() {
      if (!this.districtId) { this.$modal.showToast('请先选择区'); return; }
      const province = (this.deptTree[0].children || []).find(p => p.id === this.provinceId);
      if (!province) return;
      const city = (province.children || []).find(c => c.id === this.cityId);
      if (!city) return;
      const district = (city.children || []).find(d => d.id === this.districtId);
      if (!district) return;
      const townList = district.children || [];
      const names = townList.map(t => t.label);
      uni.showActionSheet({
        itemList: names,
        success: async ({tapIndex}) => {
          this.townName = townList[tapIndex].label;
          this.townId = townList[tapIndex].id;
          this.villageName = this.villageId = '';
          await this.fetchPriceList(this.townId);
          // 获取门卡价格
          await this.fetchCardPrice(this.townId);
          this.saveFormDataToCache();
        }
      });
    },
    async fetchPriceList(townId) {
      try {
        const res = await getDeptPrice(townId);
        if (res.code === 200 && res.data && res.data.priceList && res.data.priceList.length) {
          this.priceList = res.data.priceList;
          this.selectedPrice = this.priceList[0];
          this.saveFormDataToCache();
        } else {
          this.priceList = [];
          this.selectedPrice = null;
        }
      } catch (e) {
        this.priceList = [];
        this.selectedPrice = null;
      }
    },
    
    // 获取门卡价格
    async fetchCardPrice(deptId) {
      try {
        const res = await request({
          url: `/admin-api/door/dept/price/${deptId}`,
          method: 'get'
        });
        if (res.code === 200 && res.data) {
          const cardPrice = res.data.cardPrice || 0;
          // 更新priceList中的门卡价格
          const cardPriceItem = this.priceList.find(p => p.type === '3');
          if (cardPriceItem) {
            cardPriceItem.price = cardPrice;
          } else {
            // 如果没有门卡价格项，添加一个
            this.priceList.push({
              type: '3',
              price: cardPrice,
              name: '门禁卡'
            });
          }
          this.saveFormDataToCache();
          console.log('获取门卡价格成功:', cardPrice);
        } else {
          console.log('获取门卡价格失败:', res.msg);
        }
      } catch (e) {
        console.error('获取门卡价格异常:', e);
      }
    },
    async selectVillage() {
      if (!this.townId) { this.$modal.showToast('请先选择镇街'); return; }
      const province = (this.deptTree[0].children || []).find(p => p.id === this.provinceId);
      if (!province) return;
      const city = (province.children || []).find(c => c.id === this.cityId);
      if (!city) return;
      const district = (city.children || []).find(d => d.id === this.districtId);
      if (!district) return;
      const town = (district.children || []).find(t => t.id === this.townId);
      if (!town) return;
      const villageList = town.children || [];
      const names = villageList.map(v => v.label);
      uni.showActionSheet({
        itemList: names,
        success: ({tapIndex}) => {
          this.villageName = villageList[tapIndex].label;
          this.villageId = villageList[tapIndex].id;
          this.saveFormDataToCache();
        }
      });
    },
    selectPrice(price) {
      this.selectedPrice = price;
    },
    onQuantityInput(e) {
      let val = e.detail.value.replace(/[^\d]/g, '');
      if (val.length > 5) {
        val = val.slice(0, 5);
        uni.showToast({ title: '最多输入5位整数', icon: 'none' });
      }
      // 去除前导0
      val = val.replace(/^0+(?!$)/, '');
      this.quantity = val;
      this.saveFormDataToCache();
    },
    
    onPhoneNumberInput() {
      this.saveFormDataToCache();
    },
    
    // 验证手机号或固定电话
    isValidPhone(phone) {
      if (!phone) return false;
      
      // 手机号验证：1开头，第二位3-9，总共11位
      const mobileRegex = /^1[3-9]\d{9}$/;
      
      // 固定电话验证：
      // 1. 区号3-4位（0开头）+ 7-8位号码，可选中间的横线
      // 2. 支持格式：0755-12345678、075512345678、021-1234567、02112345678等
      const landlineRegex = /^0\d{2,3}-?\d{7,8}$/;
      
      return mobileRegex.test(phone) || landlineRegex.test(phone);
    },
    
    async submit() {
      // 校验表单
      if (!this.provinceId) return this.$modal.showToast('请选择省');
      if (!this.cityId) return this.$modal.showToast('请选择市');
      if (!this.districtId) return this.$modal.showToast('请选择区');
      if (!this.townId) return this.$modal.showToast('请选择镇街');
      if (!this.villageId) return this.$modal.showToast('请选择村居');
      if (!this.phoneNumber || !this.isValidPhone(this.phoneNumber)) return this.$modal.showToast('请输入正确的手机号或固定电话');
      if (!this.quantity || !/^[1-9]\d{0,4}$/.test(this.quantity)) return this.$modal.showToast('请输入整数，最多5位数');
      if (!this.priceList.length) return this.$modal.showToast('未获取到门禁卡价格');
      const priceObj = this.priceList.find(p => p.type === '3');
      if (!priceObj) return this.$modal.showToast('未获取到门禁卡单价');
      try {
        const orderParams = {
          address: `${this.provinceName}/${this.cityName}/${this.districtName}/${this.townName}/${this.villageName}`,
          buyCount: Number(this.quantity),
          chCardNo: '',
          chIdNo: '',
          openId: uni.getStorageSync('wechat_openid'),
          chMobile: this.phoneNumber,
          //存一下省市区县镇村
          chName: this.provinceName + this.cityName + this.districtName + this.townName + this.villageName,
          city: Number(this.cityId) || 0,
          country: 0,
          deptId: Number(this.townId) || 0,
          district: Number(this.districtId) || 0,
          door: '',
          houseId: 0,
          name: '',
          payChannel: 1,
          openid: uni.getStorageSync('wechat_openid'),
          phone: this.phoneNumber,
          protocolNo: '',
          province: Number(this.provinceId) || 0,
          remark: '',
          street: Number(this.townId) || 0,
          type: 3,
          unitPrice: Number(priceObj.price) || 0,
          village: Number(this.villageId) || 0,
          orderDetailList: [{
            address: `${this.provinceName}/${this.cityName}/${this.districtName}/${this.townName}/${this.villageName}`,
            buyCount: Number(this.quantity),
            city: Number(this.cityId) || 0,
            country: 0,
            deptId: Number(this.townId) || 0,
            district: Number(this.districtId) || 0,
            door: '',
            houseId: 0,
            isPolice: '0',
            name: '',
            phone: this.phoneNumber,
            province: Number(this.provinceId) || 0,
            street: Number(this.townId) || 0,
            unitPrice: Number(priceObj.price) || 0,
            village: Number(this.villageId) || 0,
            planId: 0,
            projectPrice: 0,
            totalPrice: Number(this.quantity) * Number(priceObj.price) || 0,
            type: 3
          }]
        };
        const res = await addOrderInfo(orderParams);
        if (res.code === 200 && res.data) {
          uni.navigateTo({
            url: `/pages/mine/maintenance/payConfirm?data=${encodeURIComponent(JSON.stringify(res.data))}`
          });
        } else {
          this.$modal.showToast(res.msg || '下单失败');
        }
      } catch (e) {
        this.$modal.showToast('下单失败');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
$bg-color: #F7F8FA;
$card-bg: #fff;
$text-primary: #333;
$text-secondary: #888;
$text-placeholder: #ccc;
$divider-color: #f0f0f0;
$danger: #fa3534;
$primary: #07c160;

.accesscard-bg {
  min-height: 100vh;
  background-color: $bg-color;
  padding-top: 4rpx;
}

.card-section {
  background: $card-bg;
  border-radius: 24rpx;
  margin: 0 20rpx 20rpx 20rpx;
  padding: 4rpx 20rpx;
}

.section-title {
  font-size: 30rpx;
  color: $text-primary;
  font-weight: 600;
  padding: 24rpx 0 8rpx 0;
}

.form-group {
  padding: 0;
}

.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 0;
  font-size: 30rpx;
  position: relative;
  background: transparent;
  
  &:not(:last-child)::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 1px;
    background-color: $divider-color;
    transform: scaleY(0.5);
  }
}

.item-label {
  color: $text-primary;
  display: flex;
  align-items: center;
  font-size: 30rpx;
}

.required {
  color: $danger;
  margin-right: 8rpx;
}

.item-content {
  display: flex;
  align-items: center;
  color: $text-placeholder;
}

.input-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  flex-wrap: nowrap;
}

.placeholder {
  color: $text-placeholder;
  margin-right: 8rpx;
}

.input-field {
  text-align: right;
  font-size: 30rpx;
  width: 100%;
  color: $text-primary;
  background: transparent;
  border: none;
  padding: 0;
}

.input-placeholder {
  color: $text-placeholder;
}

.notice {
  margin: 0 32rpx;
  padding: 16rpx 24rpx;
  background: #FFF7F7;
  color: $danger;
  font-size: 26rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 32rpx;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.05);
  z-index: 100;
  padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
}

.total {
  font-size: 28rpx;
  color: $text-secondary;
  display: flex;
  align-items: baseline;
  flex: 1;
}

.amount {
  color: $danger;
  font-weight: bold;
  font-size: 36rpx;
  margin-left: 8rpx;
}

.buy-button {
  background-color: $primary;
  color: white;
  border: none;
  border-radius: 40rpx;
  padding: 0 48rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 30rpx;
  font-weight: 500;
  
  &::after {
    border: none;
  }
  
  &:active {
    background-color: #05a54c;
  }
}

.select-value {
  color: #bbb;
  font-size: 30rpx;
}

.select-value.selected {
  color: #222;
  font-weight: bold;
}

.price-select-row {
  display: flex;
  gap: 18rpx;
  margin-top: 12rpx;
}

.price-tag {
  background: #f7f8fa;
  border-radius: 32rpx;
  padding: 8rpx 28rpx;
  display: flex;
  align-items: center;
  border: 2rpx solid #e0e0e0;
  cursor: pointer;
  transition: border 0.2s, background 0.2s;
}

.price-tag.selected {
  border: 2rpx solid #07c160;
  background: #eafaf3;
}

.price-value {
  color: #222;
  font-size: 30rpx;
  font-weight: bold;
  margin-right: 4rpx;
}

.price-unit {
  color: #888;
  font-size: 26rpx;
}

.single-price {
  color: #888;
  font-size: 28rpx;
  margin-left: 18rpx;
  white-space: nowrap;
}
</style> 